import { useState, useEffect, useCallback, useRef } from 'react';
import type { GetProp } from 'antd';
import type { Attachments } from '@/components';
import { createConversation, ConversationDTO } from '@/api/conversation';
import { getAllMessages, getAllMessagesByconversation, MessageDTO } from '@/api/message';
import { useStreamChat } from './useStreamChat';

export interface ChatMessage {
  id: string;
  role: 'USER' | 'ASSISTANT';
  content: string;
  status: 'success' | 'error';
  reasonContent: string;
}

export interface ChatResult {
  content: string;
  reasonContent: string;
}

/**
 * useChat Hook 的配置选项
 */
export interface UseChatOptions {
  /** 消息发送成功的回调函数 */
  onSuccess?: () => void;
}

/**
 * 聊天功能的核心 Hook
 * 
 * @param options - Hook 的配置选项
 * @returns 聊天相关的状态和方法
 * 
 */
export const useChat = (options: UseChatOptions = {}) => {
  // ==================== State ====================
  /** 输入框内容 */
  const [content, setContent] = useState('');
  /** 附件面板开关状态 */
  const [headerOpen, setHeaderOpen] = useState(false);
  /** 已上传的文件列表 */
  const [attachedFiles, setAttachedFiles] = useState<GetProp<typeof Attachments, 'items'>>([]);
  /** 当前对话 */
  const [conversation, setConversation] = useState<ConversationDTO | null>(null);

  const conversationRef = useRef(conversation); // 初始化 current 为 0
  /** 历史消息加载状态 */
  const [loadingHistory, setLoadingHistory] = useState(false);
  /** 历史消息加载错误 */
  const [historyError, setHistoryError] = useState<string | null>(null);
  /** 消息列表 */
  const [messages, setMessages] = useState<ChatMessage[]>([]);

  const { streamChat, streaming, error } = useStreamChat();
  
  useEffect(() => {
    conversationRef.current = conversation; // 更新 current（不触发渲染）
  }, [conversation]);
  // 重置消息列表
  const resetMessages = useCallback(() => {
    setMessages([]);
    setHistoryError(null);
  }, []);

  // 设置会话时重置消息，除非会话ID相同
  // useEffect(() => {
  //   if (!conversation) {
  //     resetMessages();
  //   }
  // }, [conversation, resetMessages]);

  // 加载对话历史消息
  useEffect(() => {
    const loadMessages = async () => {
      // 如果没有会话ID，重置消息列表
      if (!conversation?.id) {
        resetMessages();
        return;
      }

      // 开始加载
      setLoadingHistory(true);
      setHistoryError(null);

      try {
        console.log('加载会话历史消息:', conversation.id);
        const historyMessages = await getAllMessagesByconversation(conversation.id);
        console.log('获取到历史消息:', historyMessages);

        if (!historyMessages || historyMessages.length === 0) {
          console.log('没有历史消息');
          setMessages([]);
          return;
        }

        // 按创建时间排序
        const sortedMessages = historyMessages.sort((a, b) => 
          new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
        );
        
        // 转换为内部消息格式
        const formattedMessages = sortedMessages.map(msg => ({
          id: msg.id,
          role: msg.role,
          content: msg.content || '',
          reasonContent: msg.reasonContent || '',
          status: 'success',
        }));

        console.log('处理后的消息:', formattedMessages);
        setMessages(formattedMessages as ChatMessage[]);
      } catch (error) {
        console.error('加载历史消息失败:', error);
        setHistoryError('加载历史消息失败，请稍后重试');
      } finally {
        setLoadingHistory(false);
      }
    };

    loadMessages();
  }, [conversation?.id, resetMessages]);

  // ==================== Events ====================
  /**
   * 处理消息发送
   * @param nextContent - 要发送的消息内容
   */
  const handleSubmit = async (nextContent: string) => {
    if (!nextContent) return;
    
    const aiMessageId = (new Date()).valueOf().toString();
    const userMessageId = (new Date()).valueOf().toString() + '_u';

    try {
     
      // 如果没有当前会话，创建一个新会话    

      // 添加用户消息
      const userMessage: ChatMessage = {
        id: userMessageId,
        role: 'USER',
        content: nextContent,
        status: 'success',
        reasonContent: ''
      };

      // 添加一个空的 AI 消息用于实时更新
      const aiMessage: ChatMessage = {
        id: aiMessageId,
        role: 'ASSISTANT',
        content: '',
        status: 'success',
        reasonContent: ''
      };

      // 添加消息到列表
      setMessages(prev => [...prev, userMessage, aiMessage]);

      console.log('开始流式响应');
      // 处理 AI 响应
      // await streamChat(nextContent, currentConversation.id, ({content, reasonContent}: ChatResult) => {
      //   // 更新 AI 消息内容
      //   setMessages(prev => prev.map(msg => 
      //     msg.id === aiMessageId 
      //       ? { ...msg, content, reasonContent }
      //       : msg
      //   ));
      // });

      await setTimeout(() => {
        setMessages(prev => prev.map(msg => 
          msg.id === aiMessageId 
            ? { ...msg, content: 'AI 消息内容', reasonContent: 'AI 消息原因' }
            : msg
        ));
      }, 1000);

      // 清空输入框
      setContent('');
      options.onSuccess?.();
      
      console.log('消息发送完成');
    } catch (error) {
      console.error('发送消息失败:', error);
      // 更新消息状态为错误
      setMessages(prev => prev.map(msg => 
        msg.id === aiMessageId 
          ? { ...msg, status: 'error' }
          : msg
      ));
    }
  };

  /**
   * 处理文件变更
   * @param info - 文件变更信息
   */
  const handleFileChange: GetProp<typeof Attachments, 'onChange'> = (info) =>
    setAttachedFiles(info.fileList);

  return {
    content,
    setContent,
    headerOpen,
    setHeaderOpen,
    attachedFiles,
    messages,
    setMessages,
    loading: streaming || loadingHistory,
    loadingHistory,
    historyError,
    handleSubmit,
    handleFileChange,
    conversation,
    setConversation,
    conversationRef
  };
};